package service

import (
	"encoding/json"
	"errors"
	"hello/model"
	"log"
	"time"
)

type MessageService struct {
	message *model.Message
}

func (s *MessageService) parseJson(data []byte) error {
	return json.Unmarshal(data, &s.message)
}

//发送消息
func  (s *MessageService) Send() error  {
	err := errors.New("")
	//判断是私聊还是群聊
	switch s.message.Cmd {
	case model.CMD_SINGLE_MSG:
		err =  s.sendToConact()
	case model.CMD_ROOM_MS:
		err =  s.sendMsgToComm()
	case model.CMD_HEART:
		err = s.sendToHeart()
		return err
	default:
		log.Println("无法检测到私聊还是群聊")
	}
	if err != nil && err.Error() != "" {
		return err
	}

	return s.save()
}
//好友发送
func  (s *MessageService) sendToConact() error  {
	node, ok := ClientMap[s.message.DstId]
	if !ok {
		return nil
	}
	msg, err := json.Marshal(s.message)
	if err != nil {
		return err
	}
	return node.SendMsg(msg)
}
//群发送消息
func (s *MessageService) sendMsgToComm() error  {
	//获取当前所有可用的userId
	userIds := make([]int64, 0)
	for userId, _ := range ClientMap {
		if userId == s.message.UserId {
			continue
		}
		userIds = append(userIds, userId)
	}
	onlineUserIds, err := LoadAllOnlineUserIdsByCommunity(userIds, s.message.DstId)
	if err != nil {
		return err
	}
	msg, err := json.Marshal(s.message)
	if err != nil {
		return err
	}
	for _, userId := range onlineUserIds {
		if node, ok := ClientMap[int64(userId)]; ok{
			node.SendMsg(msg)
		}
	}

	return nil
}

//心跳信息
func (s * MessageService) sendToHeart() error  {
	node, ok := ClientMap[s.message.UserId]
	if !ok {
		return nil
	}
	msg, err := json.Marshal(s.message)
	if err != nil {
		return err
	}
	return node.SendMsg(msg)
}

//保存发送过的message
func (s * MessageService) save() error  {
	s.message.CreatedAt = time.Now()
	_, err := DbEngin.InsertOne(s.message)
	return err
}